<template>
  <div class="content-detail">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header
          icon="el-icon-arrow-left"
          content="创建新项目"
          @back="goback"
        >
        </el-page-header>
        <div class="card-box--downloadbtn">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box mana-content">
      <template #header>
        <div class="card-box-header">
          <span>项目基础信息</span>

          <div v-if="showInfo" @click="showInfo = !showInfo" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="showInfo = !showInfo" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <el-form
          :model="formData"
          class="content-box"
          :rules="rules"
          ref="formDataRef"
          label-width="200px"
          v-show="showInfo"
          @click="handleDeptList(false)"
        >
          <el-form-item label="项目类型" prop="projectTypeCode">
            <el-select
              v-model="formData.projectTypeCode"
              value-key="dicCode"
              @change="handleChangeType"
              class="width-custom200"
              :disabled="!!projectId"
            >
              <el-option
                class="default-option"
                v-for="item in projectTypeList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="申报类型"
            prop="declareType"
            v-if="isTypeB || isOldTypeB"
          >
            <el-select v-model="formData.declareType" class="width-custom200">
              <el-option
                class="default-option"
                v-for="item in sbOptions"
                :label="item.label"
                :key="item.value"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="项目名称" prop="projectName">
            <el-input
              v-model.trim="formData.projectName"
              class="width-custom200"
            ></el-input>
            <div class="tip text">
              （一）A类项目名称规则：A类-片区-工厂-年份-项目名称（指总项目名称）。例如，A类-山东区域-济南工厂-2021-70万千升/年新建项目<br />
              （二）B类项目名称规则：B类-片区-工厂-年份-专项-部门及项目名称。例如：B类-华东片区-滨州工厂-2021-装备升级专项-包装B线洗瓶机喷淋系统改造项目
            </div>
          </el-form-item>

          <el-form-item label="项目编号" prop="projectCode" v-if="isTypeB">
            <el-input
              v-model.trim="formData.projectCode"
              class="width-custom200"
            ></el-input>
            <!-- <div class="tip text">
              （一）A类项目编号规则：A类：A类-XX-XX-2023-01。例如：A类-SD-JN-2021-01<br />
              （二）B类项目编号规则：B类：B类-XX-XX-2023-01。例如：A类-SN-SD-2023-01
            </div> -->
          </el-form-item>

          <el-form-item
            label="项目性质"
            prop="projectNatureCode"
            v-if="isTypeB"
          >
            <el-select
              v-model="formData.projectNatureCode"
              value-key="dicCode"
              class="width-custom200"
            >
              <el-option
                class="default-option"
                v-for="item in projectNatureList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item"
                clearable
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="费用专项类型"
            prop="typeName"
            v-if="isTypeB || isOldTypeB"
          >
            <el-select
              v-model="formData.typeName"
              value-key="dicCode"
              class="width-custom200"
              @change="typeNameChange"
            >
              <template v-for="item in expenseTypeList">
                <el-option
                  :key="item.dicCode"
                  v-if="!item.disabled"
                  class="default-option"
                  :label="item.dicValue"
                  :value="item"
                  clearable
                  :disabled="item.disabled"
                ></el-option>
              </template>
            </el-select>
          </el-form-item>

          <el-form-item
            label="投资方向"
            prop="investmentTypeCode"
            v-if="isTypeB || isOldTypeB"
          >
            <el-select
              v-model="formData.investmentTypeCode"
              value-key="dicCode"
              class="width-custom200"
            >
              <el-option
                class="default-option"
                v-for="item in inverstmentTypeList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item"
                clearable
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="项目批准金额(万元)" prop="approvalAmount">
            <!-- <el-input
              v-model.trim="formData.approvalAmount"
              class="width-custom200"
              placeholder="请输入项目金额"
            ></el-input> -->
            <el-input-number
              v-model="formData.approvalAmount"
              :min="0"
              :max="999999999.999999"
              precision="6"
              style="width: 200px"
              :controls="false"
              placeholder="请输入项目金额"
            ></el-input-number>
          </el-form-item>

          <el-form-item label="立项是否含资产调拨" v-if="isTypeB">
            <el-radio-group :aria-label="false" v-model="haveTransferAmount">
              <el-radio :label="'0'">否</el-radio>
              <el-radio :label="'1'">是</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="调拨资产金额(含税，万元)"
            prop="transferAmount"
            v-if="isTypeB && haveTransferAmount === '1'"
          >
            <el-input-number
              v-model="formData.transferAmount"
              :min="0"
              :max="999999999.9999"
              precision="4"
              style="width: 200px"
              :controls="false"
              placeholder="请输入调拨资产金额"
            ></el-input-number>
            <div class="tip text">
              备注：资产调拨金额填写的为不占用当年度B类项目规划额度的金额。
            </div>
          </el-form-item>

          <el-form-item
            label="立项需求批准日期"
            prop="approvalDate"
            v-if="isTypeB"
          >
            <el-date-picker
              v-model="formData.approvalDate"
              type="date"
              placeholder="请选择日期"
              class="width-custom200"
              value-format="YYYY-MM-DD"
              clearable
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="立项批准日期" prop="approvalTime">
            <el-date-picker
              v-model="formData.approvalTime"
              type="date"
              placeholder="请选择日期"
              class="width-custom200"
              value-format="YYYY-MM-DD"
              clearable
            ></el-date-picker>
          </el-form-item>

          <el-form-item
            label="项目预计完成日期"
            prop="planCompletionDate"
            v-if="isTypeB"
          >
            <el-date-picker
              v-model="formData.planCompletionDate"
              type="date"
              placeholder="请选择日期"
              class="width-custom200"
              value-format="YYYY-MM-DD"
              clearable
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="项目所属单位" prop="projectFactoryCode">
            <el-input
              v-model.trim="filterText"
              class="width-custom200"
              @click.stop="handleDeptList(true)"
            ></el-input>
            <el-tree
              clearable
              ref="treeRef"
              class="filter-tree"
              :data="deptList"
              :props="defaultProps"
              default-expand-all
              :filter-node-method="filterNode"
              v-if="showDeptList"
              @node-click="handleChangeDept"
            />
          </el-form-item>
          <el-form-item label="项目管理员" prop="projectLeaderId">
            <el-select
              v-model="formData.projectLeaderId"
              filterable
              remote
              placeholder="请输入姓名"
              :remote-method="getTableData"
              class="width-custom200"
            >
              <el-option
                v-for="item in userList"
                :key="item.value"
                :label="item.label"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目年度" prop="projectYear">
            <el-date-picker
              v-model="formData.projectYear"
              type="year"
              value-format="YYYY"
              placeholder="项目年度"
              class="width-custom200"
            ></el-date-picker>
            <span class="tip">
              注意：项目类型为A类项目时，选择项目立项的年份。
            </span>
          </el-form-item>
          <!-- 现在没有B了 -->
          <!-- <el-form-item
            label="项目模板"
            prop="projectTmpId"
            v-if="formData.projectTypeCode.dicCode === 'B'"
          >
            <el-select
              v-model="formData.projectTmpId"
              value-key="id"
              class="width-custom200"
              @change="handleChangeTemp"
            >
              <el-option
                class="default-option"
                v-for="item in templateList"
                :label="item.projectTemplateName"
                :key="item.id"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item label="审批附件" required v-if="false"></el-form-item>
          <div class="field-group-box" v-if="false">
            <el-form-item label="立项需求表及附件" prop="requireAttachments">
              <ecm-upload
                ref="requireAttachmentsRef"
                :files="requireAttachments"
                :docid="docid"
                @set-file="
                  fileList => handleSuccess(fileList, 'requireAttachments')
                "
              ></ecm-upload>
            </el-form-item>
            <el-form-item label="立项审批表及附件" prop="approvalAttachments">
              <ecm-upload
                ref="approvalAttachmentsRef"
                :files="approvalAttachments"
                :docid="docid"
                @set-file="
                  fileList => handleSuccess(fileList, 'approvalAttachments')
                "
              ></ecm-upload>
            </el-form-item>
            <el-form-item label="其他文件" prop="otherAttachments">
              <ecm-upload
                ref="otherAttachmentsRef"
                :files="otherAttachments"
                :docid="docid"
                @set-file="
                  fileList => handleSuccess(fileList, 'otherAttachments')
                "
              ></ecm-upload>
            </el-form-item>
          </div>
          <el-form-item label="项目描述" prop="remarks">
            <el-input
              type="textarea"
              v-model.trim="formData.remarks"
              :rows="3"
            ></el-input>
          </el-form-item>
        </el-form>
      </el-collapse-transition>
    </el-card>
    <!-- <el-card class="card-box" v-if="formData.projectTmpId"> -->
    <el-card class="card-box" v-if="false">
      <template #header>
        <div class="card-box-header">
          <span>项目模版配置</span>

          <div v-if="showSet" @click="showSet = !showSet" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="showSet = !showSet" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <div v-show="showSet" class="content-box">
          <status-task-edit
            ref="editRef"
            :mode="isEdit ? 'edit' : 'read'"
            :templateId="templateId"
            :data="proStageList"
            :checkbox="true"
          ></status-task-edit>
        </div>
      </el-collapse-transition>
    </el-card>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  reactive,
  toRefs,
  watch,
  nextTick,
  computed,
  onMounted
} from "vue";
import { useRoute, useRouter } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import { getUserList } from "/@/api/user";
import EcmUpload from "/@/components/ecmUpload/index.vue";
import { onFilterFileData } from "/@/utils/file";
import {
  addProject,
  projectTemplateList,
  getDeptTree,
  getTemplateInfo,
  getProjectDetailApi,
  updateProjectDetailApi
} from "/@/api/projects";
import { postDictList } from "/@/api/home";
import { ElMessageBox } from "element-plus";
import StatusTaskEdit from "../../../components/template/index.vue";
import { clickEvent } from "/@/utils/func";
export default defineComponent({
  components: { StatusTaskEdit, EcmUpload },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const formDataRef = ref<HTMLFormElement | null>(null) as any;
    const editRef = ref<HTMLFormElement | null>(null) as any;
    const treeRef = ref<HTMLFormElement | null>(null) as any;
    let userList = ref([]);
    let projectTypeList = ref([]);
    let templateList = ref([]);
    let deptList = ref([]);
    let expenseTypeList = ref([]);
    let docid = window["ecmDocType"].project;
    const requireAttachments = ref([]);
    const approvalAttachments = ref([]);
    const otherAttachments = ref([]);
    const sbOptions = ref([
      { label: "临时申报", value: "0" },
      { label: "集中申报", value: "1" }
    ]);

    let state = reactive({
      formData: {
        // projectCode: "",
        projectLeaderId: "" as any,
        projectLeaderName: "",
        projectName: "",
        projectCode: "",
        declareType: "",
        projectNatureCode: "" as any,
        investmentTypeCode: "" as any,
        approvalDate: "",
        approvalTime: "",
        planCompletionDate: "",
        projectTmpId: null,
        projectTypeCode: {} as any,
        projectTypeName: "",
        approvalAmount: undefined,
        typeName: "" as any,
        projectRegionCode: "",
        projectRegionName: "",
        projectFactoryCode: "",
        projectFactoryName: "",
        projectYear: "",
        remarks: "",
        requireAttachments: [],
        approvalAttachments: [],
        otherAttachments: [],
        transferAmount: undefined
      },
      showInfo: true,
      showSet: true,
      defaultProps: {
        children: "children",
        label: "deptDescShrt"
      },
      showDeptList: false
    });

    let stageCheckedkeys = ref([]);
    let taskCheckedkeys = ref([]);
    let isEdit = true;
    let templateId = ref();
    let projectTemplateInfo = {};
    const filterNode = (value: string, data) => {
      if (!value) return true;
      return data.deptDescShrt.includes(value);
    };

    let haveTransferAmount = ref("0");
    let proStageList = ref([]);

    const projectNatureList = ref([]);
    const inverstmentTypeList = ref([]);

    const rules = {
      projectName: [
        { required: true, message: "请填写项目名称", trigger: "blur" },
        { min: 3, max: 300, message: "长度在 3 到 300 个字符", trigger: "blur" }
      ],
      projectCode: [
        { required: true, message: "请填写项目编号", trigger: "blur" }
      ],
      projectNatureCode: [
        { required: true, message: "请选择项目性质", trigger: "blur" }
      ],
      investmentTypeCode: [
        { required: true, message: "请选择投资方向", trigger: "blur" }
      ],
      approvalAmount: [
        {
          required: true,
          message: "仅支持数字填写，且小数位最多保留6位！",
          trigger: "blur"
        }
      ],
      transferAmount: [
        { required: true, message: "请填写调拨资产金额", trigger: "blur" },
        {
          validator(rule: any, value: any, callback: any) {
            const max = state.formData.approvalAmount || 999999999.9999;
            if (value > max) {
              callback(new Error(`调拨资产金额不能大于项目批准金额`));
            } else {
              callback();
            }
          },
          trigger: "blur"
        }
      ],
      approvalDate: [
        { required: true, message: "请选择立项需求批准日期", trigger: "blur" }
      ],
      projectTypeCode: [
        { required: true, message: "请选择项目类型", trigger: "change" }
      ],
      declareType: [
        { required: true, message: "请选择申报类型", trigger: "change" }
      ],
      approvalTime: [
        { required: true, message: "请选择日期", trigger: "change" }
      ],
      planCompletionDate: [
        { required: true, message: "请选择项目预计完成日期", trigger: "change" }
      ],
      projectFactoryCode: [
        { required: true, message: "请选择项目所属工厂", trigger: "change" }
      ],
      projectLeaderId: [
        { required: true, message: "请填写项目管理员", trigger: "change" }
      ],
      projectYear: [
        { required: true, message: "请选择项目年度", trigger: "change" }
      ],
      typeName: [
        { required: true, message: "请选择费用专项类型", trigger: "blur" }
      ],
      projectTmpId: [
        { required: true, message: "请选择项目模板", trigger: "change" }
      ],
      requireAttachments: [
        { required: true, message: "请上传立项需求表及附件", trigger: "change" }
      ],
      approvalAttachments: [
        { required: true, message: "请上传立项审批表及附件", trigger: "change" }
      ]
    };

    const filterText = ref("");
    watch(filterText, val => {
      if (treeRef.value && treeRef.value.length) {
        treeRef.value!.filter(val);
      }
    });

    const projectId = ref<string>("");
    onMounted(() => {
      projectId.value = route.query.id as string;
      getSelectList();
    });

    const getSelectList = () => {
      const promises = [
        initProjectTypeList(),
        initProjectNatureList(),
        initExpenseTypeList(),
        initInverstmentTypeList("")
      ];
      // 等选择项请求回来之后再去请求详情
      Promise.all(promises).then(() => {
        if (projectId.value) {
          queryProjectDetail(projectId.value);
        }
      });
    };

    // 获取详情
    const queryProjectDetail = async id => {
      let find = null;
      try {
        const { data } = await getProjectDetailApi(id);
        userList.value = [
          {
            label: data.projectLeaderName,
            value: data.projectLeaderId
          }
        ];
        // B类资产调拨
        if (data.transferAmount || data.transferAmount === 0) {
          haveTransferAmount.value = "1";
          state.formData.transferAmount = Number(data.transferAmount);
        }
        // projectNatureList 项目性质
        find = projectNatureList.value.find((val: any) => {
          return val.dicCode === data.projectNatureCode;
        });
        state.formData.projectNatureCode = find
          ? {
              dicCode: data.projectNatureCode,
              dicValue: data.projectNatureName
            }
          : "";
        // expenseTypeList 费用类型
        find = expenseTypeList.value.find((val: any) => {
          return val.dicCode === data.expensesTypeCode;
        });
        state.formData.typeName = find
          ? {
              dicCode: data.expensesTypeCode,
              dicValue: data.expensesTypeName
            }
          : "";
        // projectTypeList 项目类型
        find = projectTypeList.value.find((val: any) => {
          return val.dicCode === data.projectTypeCode;
        });
        state.formData.projectTypeCode = find
          ? {
              dicCode: data.projectTypeCode,
              dicValue: data.projectTypeName
            }
          : "";
        // inverstmentTypeList 投资方向
        find = inverstmentTypeList.value.find((val: any) => {
          return val.dicCode === data.investmentTypeCode;
        });
        state.formData.investmentTypeCode = find
          ? {
              dicCode: data.investmentTypeCode,
              dicValue: data.investmentTypeName
            }
          : "";
        state.formData.projectLeaderId = {
          label: data.projectLeaderName,
          value: data.projectLeaderId
        };
        state.formData.requireAttachments = data.requireAttachments
          ? JSON.parse(data.requireAttachments)
          : [];
        state.formData.approvalAttachments = data.approvalAttachments
          ? JSON.parse(data.approvalAttachments)
          : [];
        state.formData.otherAttachments = data.otherAttachments
          ? JSON.parse(data.otherAttachments)
          : [];
        state.formData.projectRegionCode = data.projectRegionCode;
        state.formData.projectRegionName = data.projectRegionName;
        state.formData.projectFactoryCode = data.projectFactoryCode;
        state.formData.projectFactoryName = data.projectFactoryName;
        filterText.value = data.projectFactoryName;
        state.formData.approvalAmount = data.approvalAmount;
        state.formData.projectLeaderName = data.projectLeaderName;
        state.formData.projectName = data.projectName;
        state.formData.projectCode = data.projectCode;
        state.formData.approvalDate = data.approvalDate;
        state.formData.approvalTime = data.approvalTime;
        state.formData.planCompletionDate = data.planCompletionDate;
        state.formData.projectTmpId = data.projectTmpId;
        state.formData.projectTypeName = data.projectTypeName;
        state.formData.projectYear = data.projectYear;
        state.formData.remarks = data.remarks;
        state.formData.declareType = data.declareType;
      } catch (err) {
        console.log(err);
      }
    };

    // 项目类型
    const initProjectTypeList = async () => {
      return new Promise((resolve, reject) => {
        try {
          postDictList({ dicType: "thd_pro_type" }).then((res: any) => {
            const { data } = res;
            projectTypeList.value = (data || []).filter(
              (item: any) =>
                projectId.value ? true : ["A", "B0"].includes(item.dicCode) // 新增只需要A类B类
            );
            if (projectId.value) {
              resolve(null);
              return;
            }
            state.formData.projectTypeCode = projectTypeList.value.find(
              item => item.dicCode === "B0"
            );
            resolve(null);
          });
        } catch (err) {
          console.log(err);
          reject(null);
        }
      });
    };

    // 项目类型
    const initProjectNatureList = async () => {
      return new Promise((resolve, reject) => {
        try {
          postDictList({ dicType: "thd_pro_nature" }).then((res: any) => {
            const { data } = res;
            projectNatureList.value = data || [];
            resolve(null);
          });
        } catch (err) {
          console.log(err);
          reject(null);
        }
      });
    };
    // 费用类型
    const initExpenseTypeList = async () => {
      return new Promise((resolve, reject) => {
        try {
          postDictList({ dicType: "thd_expenses_type" }).then((res: any) => {
            const { data } = res;
            expenseTypeList.value =
              data.filter((item: any) => !item.disabled) || [];
            resolve(null);
          });
        } catch (err) {
          console.log(err);
          reject(null);
        }
      });
    };
    // 投资方向
    const initInverstmentTypeList = async (pid: any) => {
      return new Promise((resolve, reject) => {
        try {
          postDictList({
            dicType: "thd_pro_investment",
            pid
          }).then((res: any) => {
            const { data } = res;
            inverstmentTypeList.value = data || [];
            resolve(null);
          });
        } catch (err) {
          console.log(err);
          reject(null);
        }
      });
    };
    const typeNameChange = (e: any) => {
      initInverstmentTypeList(e.id);
      state.formData.investmentTypeCode = "";
    };

    // 工厂区域
    const getDeptTreeFunc = async () => {
      try {
        const { data } = await getDeptTree({});
        deptList.value = data || [];
      } catch (err) {
        console.log(err);
      }
    };
    getDeptTreeFunc();

    // 模板类型
    const initTemplateTypeList = async code => {
      try {
        const { data } = await projectTemplateList({
          isOriginal: "1",
          projectTemplateNameLike: "",
          projectTmpTypeCode: code || "",
          createUserNameLike: "",
          createTimeStrStart: "",
          createTimeStrEnd: "",
          pageNum: 1,
          pageSize: 0
        });
        templateList.value = data.list || [];
      } catch (err) {
        console.log(err);
      }
    };

    const handleChangeType = () => {
      let tmpTypeCode = state.formData.projectTypeCode;
      let code = tmpTypeCode ? tmpTypeCode.dicCode : "";
      if (code === "B") {
        initTemplateTypeList(code);
      } else {
        state.formData.projectTmpId = null;
      }
    };

    const goback = () => {
      router.push("/projects/manage/space");
    };

    const getTableData = async (query = "") => {
      if (!query) {
        userList.value = [];
        return;
      }
      try {
        const params = {
          pageNum: 1,
          pageSize: 100,
          nameLike: query
        };
        const { code, data } = await getUserList(params);
        if (code === 200) {
          userList.value = data.list.map(item => {
            return { value: item.id, label: `${item.name}(${item.userName})` };
          });
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleSave = async () => {
      try {
        const isValid = await new Promise(resolve =>
          formDataRef.value.validate(resolve)
        );
        if (!isValid) return;
        if (state.formData.projectTmpId) {
          // editRef.value
          //   .save()
          //   .then(async data => {
          //     // 简化data中的参数
          //     let arr = [];
          //     data.forEach((item, index) => {
          //       let obj = {
          //         index,
          //         projectStageName: item.projectStageName
          //       } as any;
          //       let taskList = [];
          //       item.proTmpTaskList.forEach(task => {
          //         let taskObj = {
          //           approvalForm: task.approvalForm,
          //           approvalNodeCode: task.approvalNodeCode,
          //           approvalNodeName: task.approvalNodeCode,
          //           approvalNodeTmpAttachmentArr:
          //             task.approvalNodeTmpAttachmentArr,
          //           taskName: task.taskName
          //         };
          //         taskList.push(taskObj);
          //       });
          //       obj.proTmpTaskList = [...taskList];
          //       arr.push(obj);
          //     });
          //     submitAddProject(arr);
          //   })
          //   .catch(err => {
          //     console.log("error", err);
          //     NotifMessage.warning(err);
          //   });
          submitAddProject(proStageList.value);
        } else {
          let arr = [];
          submitAddProject(arr);
        }
      } catch (err) {
        console.log(err, "00000");
      }
    };

    const submitAddProject = arr => {
      const params = {
        ...state.formData,
        projectTmpId: state.formData.projectTmpId?.id,
        projectTypeName: state.formData.projectTypeCode?.dicValue,
        projectTypeCode: state.formData.projectTypeCode?.dicCode,
        projectNatureCode: state.formData.projectNatureCode?.dicCode,
        projectNatureName: state.formData.projectNatureCode?.dicValue,
        investmentTypeCode: state.formData.investmentTypeCode?.dicCode,
        investmentTypeName: state.formData.investmentTypeCode?.dicValue,
        projectLeaderName: state.formData.projectLeaderId?.label,
        projectLeaderId: state.formData.projectLeaderId?.value + "",
        projectRegionCode: state.formData.projectRegionCode,
        projectRegionName: state.formData.projectRegionName,
        projectFactoryCode: state.formData.projectFactoryCode,
        projectFactoryName: state.formData.projectFactoryName,
        requireAttachments: JSON.stringify(
          onFilterFileData(state.formData.requireAttachments)
        ),
        approvalAttachments: JSON.stringify(
          onFilterFileData(state.formData.approvalAttachments)
        ),
        otherAttachments: JSON.stringify(
          onFilterFileData(state.formData.otherAttachments)
        ),
        newProjectTemplate: {
          ...projectTemplateInfo,
          proStageList: arr
        },
        expensesTypeName: state.formData.typeName?.dicValue,
        expensesTypeCode: state.formData.typeName?.dicCode
      };
      const { projectTypeCode } = state.formData;
      if (
        projectTypeCode?.dicCode !== "B0" ||
        haveTransferAmount.value !== "1"
      ) {
        params.transferAmount = "";
      }
      ElMessageBox.confirm("保存后将无法修改，确认保存吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info"
      }).then(async () => {
        if (projectId.value) {
          params.id = projectId.value;
          const { code, message } = await updateProjectDetailApi(params);
          clickEvent(
            "编辑项目",
            "编辑",
            state.formData.projectTypeCode?.dicValue
          );
          commonBackFn(code, message);
          return;
        }
        const { code, message } = await addProject(params);
        clickEvent(
          "新增项目",
          "保存",
          state.formData.projectTypeCode?.dicValue
        );
        commonBackFn(code, message);
        console.log("params", params);
      });
    };

    const commonBackFn = (code: Number, message: String) => {
      if (code === 200) {
        NotifMessage.success(message);
        goback();
      } else {
        if (!message) return;
        NotifMessage.error(message);
      }
    };

    const handleDeptList = flag => {
      state.showDeptList = flag;
    };

    const handleChangeDept = (node, nodeObj) => {
      let parent = nodeObj.isLeaf && nodeObj.level == 3 && nodeObj.parent.data;
      let data = nodeObj.data;
      state.formData.projectRegionCode = parent.id;
      state.formData.projectRegionName = parent.deptDescShrt;
      state.formData.projectFactoryCode = data.id;
      state.formData.projectFactoryName = data.deptDescShrt;
      if (nodeObj.isLeaf && nodeObj.level == 3) {
        state.showDeptList = false;
        filterText.value = data.deptDescShrt;
      }
    };

    const getData = async templateId => {
      try {
        const { code, data } = await getTemplateInfo({ id: templateId });
        if (code === 200) {
          const {
            projectTemplateName,
            projectTmpTypeCode,
            projectTmpTypeName,
            remarks,
            proStageList: proStageListData
          } = data;
          projectTemplateInfo = {
            projectTemplateName,
            projectTmpTypeCode,
            projectTmpTypeName,
            remarks
          };
          proStageList.value = [...proStageListData];
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleChangeTemp = () => {
      // 请求模板数据
      let id = state.formData.projectTmpId?.id;
      templateId.value = id;
      getData(id);
      nextTick(() => {
        editRef.value.initTemFlowTypeList("thd_flow_template");
      });
    };
    const isTypeB = computed(() => {
      return state.formData.projectTypeCode.dicCode === "B0";
    });
    const isOldTypeB = computed(() => {
      return (
        state.formData.projectTypeCode.dicCode === "B" ||
        state.formData.projectTypeCode.dicCode === "B1" ||
        state.formData.projectTypeCode.dicCode === "S"
      );
    });
    const handleSuccess = (fileList, field) => {
      state.formData[field] = fileList;
    };

    watch(isTypeB, val => {
      console.log(val);
      if (!val) {
        state.formData.projectCode = "";
        state.formData.projectNatureCode = "";
        state.formData.investmentTypeCode = "";
        state.formData.approvalDate = "";
        state.formData.planCompletionDate = "";
        state.formData.typeName = "";
        state.formData.requireAttachments = [];
        state.formData.approvalAttachments = [];
        state.formData.otherAttachments = [];
      }
    });

    return {
      ...toRefs(state),
      formDataRef,
      editRef,
      userList,
      projectTypeList,
      templateList,
      rules,
      route,
      goback,
      getTableData,
      handleSave,
      handleChangeType,
      proStageList,
      haveTransferAmount,

      deptList,
      treeRef,
      handleDeptList,
      handleChangeDept,
      filterText,

      isEdit,
      templateId,

      filterNode,
      handleChangeTemp,
      stageCheckedkeys,
      taskCheckedkeys,
      expenseTypeList,
      isTypeB,
      isOldTypeB,
      handleSuccess,
      docid,
      requireAttachments,
      approvalAttachments,
      otherAttachments,
      inverstmentTypeList,
      projectNatureList,

      sbOptions,
      projectId,

      typeNameChange
    };
  }
});
</script>
<style lang="scss" scoped>
:deep .el-input-number .el-input__inner {
  text-align: left;
}
.field-group-box {
  border: 1px dashed;
  margin-bottom: 12px;
  padding-top: 12px;
}
.filter-tree:deep {
  &.el-tree {
    position: absolute;
    top: 36px;
    width: 400px;
    max-height: 226px;
    overflow: auto;
    border: 1px solid #e4e8f2;
    z-index: 10;
  }
}

.mana-content {
  padding-bottom: 50px;
}

.tip {
  font-size: 12px;
}

.tip.text {
  margin-top: 10px;
  margin-bottom: 4px;
  line-height: 20px;
  font-size: 12px;
}
</style>
